<!--
 * @Description: 商品分类信息模块
 * @Author: pinus
 * @Email: pinus0716@163.com
 * @Git: https://gitee.com/xyf97
 * @Date: 2021-10-01 11:20:02
 * @LastEditTime: 2021-10-01 11:25:37
-->
<template>
  <div class="cate-container">
    <!--  头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/wlecome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 内容card -->
    <el-card>
      <!-- 添加分类 -->
      <el-row>
        <el-col>
          <el-button type="primary"
            @click="addCate">添加分类</el-button>
        </el-col>
      </el-row>

      <!-- 分类表格 -->
      <table-tree :data="categories"
        :columns="columns"
        tree-type
        :show-row-hover="false"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="序号">
        <!-- 是否有效 -->
        <template slot="del"
          slot-scope="scope">
          <i class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: green"></i>
          <i class="el-icon-error"
            v-else
            style="color: red"></i>
        </template>
        <!-- 当前层级 -->
        <template slot="level"
          slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success"
            v-if="scope.row.cat_level === 1">二级</el-tag>
          <el-tag type="warning"
            v-if="scope.row.cat_level === 2">三级</el-tag>
        </template>
        <!-- 控制列 -->
        <template slot="ctrls"
          slot-scope="scope">
          <el-button type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="editCateInfo(scope.row)">编辑</el-button>
          <el-button type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="removeCate(scope.row.cat_id)">删除</el-button>
        </template>
      </table-tree>
      <!-- 换页区域 -->
      <el-pagination @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="cateParams.pagenum"
        :page-sizes="[5, 10, 20, 40]"
        :page-size="cateParams.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"> </el-pagination>

      <!-- // 编辑信息对话框 -->
      <el-dialog title="修改分类信息"
        :visible.sync="editDialogVisible"
        width="50%">
        <el-form :model="editForm"
          :rules="editRules"
          label-width="100px"
          ref="editForm">
          <el-form-item label="分类名称"
            prop="cat_name">
            <el-input v-model="editForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer"
          class="dialog-footer">
          <el-button @click="cancelEdit">取 消</el-button>
          <el-button type="primary"
            @click="submitEdit">确 定</el-button>
        </span>
      </el-dialog>

      <!--添加分类对话框 -->
      <el-dialog title="添加分类"
        :visible.sync="addDialogVisible"
        width="50%">
        <el-form :model="addForm"
          :rules="editRules"
          label-width="100px"
          ref="addForm">

          <el-form-item label="分类名称"
            prop="cat_name">
            <el-input v-model="addForm.cat_name"></el-input>
          </el-form-item>

          <el-form-item label="父级分类">
            <el-cascader v-model="addForm.cat_level"
              :options="levelOptions"
              :props="cascaderProps"
              @change="handelChange"
              clearable></el-cascader>
          </el-form-item>

        </el-form>
        <span slot="footer"
          class="dialog-footer">
          <el-button @click="cancelAdd">取 消</el-button>
          <el-button type="primary"
            @click="submitAddCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'Cate',
  data() {
    return {
      categories: [],
      // 表格各列的配置
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name'
        },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          type: 'template',
          template: 'del'
        },
        {
          label: '当前层级',
          prop: 'cat_level',
          type: 'template',
          template: 'level'
        },
        {
          label: '操作',
          prop: 'likes',
          type: 'template',
          template: 'ctrls'
        }
      ],
      // 编辑信息
      editDialogVisible: false,
      editForm: {
        cat_name: ''
      },
      editRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'change' },
          { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      cateId: 0,
      // 换页
      cateParams: {
        // type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      // 添加分类
      addDialogVisible: false,
      addForm: {
        cat_name: '',
        cat_level: []
      },
      levelOptions: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        expandTrigger: 'hover',
        checkStrictly: true
      }
    }
  },
  created() {
    this.getAllCategories()
    this.getSpecialCategories()
  },
  methods: {
    async getAllCategories() {
      const { data: res } = await this.$http.get('categories')

      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      // this.$message.success(res.meta.msg)
      // this.categories = res.data
      this.total = res.data.length
    },
    // 删除分类
    async removeCate(id) {
      const confirm = await this.$confirm('确认永久删除该分类吗？', '确认信息', {
        distinguishCancelAndClose: true,
        confirmButtonText: '确定',
        cancelButtonText: '放弃'
      }).catch(action => {
        this.$message({
          type: 'info',
          message: action === 'cancel' ? '删除已取消' : '停留在当前页面'
        })
      })

      if (confirm !== 'confirm') {
        return false
      }

      const { data: res } = await this.$http.delete(`categories/${id}`)

      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.getSpecialCategories()
      this.$message.success(res.meta.msg)
    },
    // 编辑信息
    editCateInfo(cate) {
      this.editForm.cat_name = cate.cat_name
      this.cateId = cate.cat_id
      this.editDialogVisible = true
    },
    // 提交编辑信息
    submitEdit() {
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          const id = this.cateId
          const { data: res } = await this.$http.put(`categories/${id}`, {
            cat_name: this.editForm.cat_name
          })

          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }

          this.getSpecialCategories()
          this.$message.success(res.meta.msg)
          this.editDialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 取消重置编辑
    cancelEdit() {
      this.$refs.editForm.resetFields()
      this.editDialogVisible = false
    },
    // 换页区域
    async getSpecialCategories() {
      const { data: res } = await this.$http.get('categories', { params: this.cateParams })

      // console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      // this.$message.success(res.meta.msg)
      this.categories = res.data.result
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.cateParams.pagesize = val
      this.getSpecialCategories()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.cateParams.pagenum = val
      this.getSpecialCategories()
    },
    // 添加分类
    async addCate() {
      const { data: res } = await this.$http.get('categories', {
        params: {
          type: 2
        }
      })

      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }

      this.levelOptions = res.data
      this.addDialogVisible = true
    },
    // 取消重置添加对话框
    cancelAdd() {
      this.$refs.addForm.resetFields()
      this.addDialogVisible = false
    },
    submitAddCate() {
      this.$refs.addForm.validate(async valid => {
        if (valid) {
          const level = this.addForm.cat_level.length
          const { data: res } = await this.$http.post('categories', {
            cat_pid: level === 0 ? 0 : this.addForm.cat_level[level - 1],
            cat_name: this.addForm.cat_name,
            cat_level: level
          })
          console.log(res)
          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }

          this.getAllCategories()
          this.getSpecialCategories()
          this.$message.success(res.meta.msg)
          this.addDialogVisible = false
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handelChange() {
      // console.log(this.addForm.cat_level)
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin-bottom: 12px;
}
.el-cascader {
  width: 100%;
}
</style>
